package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * \* User: ywg
 * \* Date: 2018/5/4
 * \* Time: 11:14
 * \* Description:
 * \
 */
public class WoTaoGateway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(WoTaoGateway.class);

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = null;
        try {
            Map<String, String> params = buildParams(entity);
            result = doPostGb2312(info.getServerAddr() + "SendSms.asp", params);
            logger.info("WoTaoGateway  sendMessage response {}, params {}", result, JSON.toJSONString(params));
            if (Integer.valueOf(result) > 0) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
            }
        } catch (Exception e) {
            logger.error("WoTaoGateway sendMessage error ! ", e);
        } finally {
            handlerResponse(entity, result, status);
        }
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        return false;
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return false;
    }

    private Map<String, String> buildParams(SendQueueEntity entity) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("Account", info.getAccount());
        paramsMap.put("Password", info.getPassword());
        // paramsMap.put("Content", URLEncoder.encode(entity.getContent(), "GB2312"));
        paramsMap.put("Content", entity.getContent());
        paramsMap.put("Phones", entity.getPhone());
        logger.info("WoTaoGateway phone {}", entity.getPhone());
        paramsMap.put("Channel", "1");
        return paramsMap;
    }

    //主动查询获取报告状态
    public boolean queryStatus() throws Exception {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(info.getServerAddr()).append("GetReport.asp");
            builder.append("?Account=").append(info.getAccount());
            builder.append("&Password=").append(info.getPassword());
            //这里不能用二次提交，因为没有状态报告的时候默认返回空
            String response = HttpClientUtil.doGet(builder.toString());
            logger.info("WoTaoGateway queryStatus url : {}, result : {}", builder.toString(), response);
            if (response != null && !response.equals("-1") && !response.equals("错误文本") && response.contains("$$$$")) {
                for (String content : response.split("\\|\\|\\|\\|")) {
                    int status = SmsMsgStatusEnum.SEND_FAIL.index;
                    String[] index = content.split("\\$\\$\\$\\$");
                    //批次号
                    String taskId = index[0];
                    String messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId + index[1]);
                    JedisService.hdel(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId + index[1]);
                    //状态标志
                    String result = index[4];
                    if ("DELIVRD".equals(result)) {
                        status = SmsMsgStatusEnum.SEND_SUCCESS.index;
                    }
                    receiveReport(status, messageId, result);
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("WoTaoGateway queryStatus error ! ", e);
        }
        return false;
    }

    //主动获取上行信息 手机号$$$$上行内容$$$$发送时间||||手机号$$$$上行内容$$$$发送时间……
    public boolean queryReceiveMsg() throws Exception {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(info.getServerAddr()).append("GetMessage.asp");
            builder.append("?Account=").append(info.getAccount());
            builder.append("&Password=").append(info.getPassword());
            //这里不能用二次提交，因为没有状态报告的时候默认返回空
            String response = HttpClientUtil.doGet(builder.toString());
            logger.info("WoTaoGateway queryReceiveMsg url : {}, result : {}", builder.toString(), response);
            if (StringUtils.isNotBlank(response) && response.contains("$$$$")) {
                for (String context : response.split("\\|\\|\\|\\|")) {
                    String[] strings = context.split("\\$\\$\\$\\$");
                    SmsReceiveMessage smsReceiveMessage = new SmsReceiveMessage();
                    smsReceiveMessage.setCreateTime(new Date());
                    smsReceiveMessage.setPhone(strings[0]);
                    smsReceiveMessage.setContent(strings[1]);
                    smsReceiveMessage.setMessageId(strings[0]);
                    receiveMessage(smsReceiveMessage);
                }
                return true;
            }
        } catch (Exception e) {
            logger.error("WoTaoGateway queryReceiveMsg error ! ", e);
        }
        return false;
    }


    @Override
    public int queryBalance() throws Exception {
        try {
            StringBuilder builder = new StringBuilder(info.getServerAddr());
            builder.append("GetBalance.asp?");
            builder.append("Account=").append(info.getAccount());
            builder.append("&Password=").append(info.getPassword());
            builder.append("&Channel=1");
            String response = HttpClientUtil.doGet(builder.toString());

            if (response != null && Integer.valueOf(response) > 0) {
                return Integer.valueOf(response);
            }
            logger.info("{}余额查询结果:{}", info.getName(), response);
        } catch (Exception e) {
            logger.error("WoTaoGateway queryBalance error ! ", e);
        }
        return 0;
    }
}
